<template>
  <div class="page-container" style="height: auto">
    <div class="in-container" style="height: auto">
      <div class="form-container">
        <el-form
          :inline="true"
          label-suffix="："
          :label-width="'100px'"
          :size="'small'"
          ref="form"
        >
          <el-row>
            <el-col :span="6">
              <el-form-item label="开票单号">
                <el-input
                  v-model="state.query.Doccode"
                  clearable
                  placeholder="请输入开票单号"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="开票对象名称" label-width="100px">
                <el-select
                  v-model="state.query.InvoiceObjId"
                  placeholder="请选择开票对象"
                  style="width: 100%"
                  clearable
                  filterable
                  remote
                  :remote-method="getBusDetail"
                  :loading="state.settlementLoading"
                >
                  <el-option
                    v-for="item in state.settlementList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <span style="float: left">{{ item.label }}</span>
                    <span style="float: right">{{ item.entFullname }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收/付">
                <el-select
                  v-model="state.query.doctype"
                  placeholder=" "
                  style="width: 100%"
                  filterable
                >
                  <el-option label="应收" :value="1"> </el-option>
                  <el-option label="应付" :value="0"> </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="发票类型" label-width="100px">
                <el-select
                  v-model="state.query.InvoiceTypeId"
                  placeholder="请选择发票类型"
                  style="width: 100%"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in state.InvoiceTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="币种">
                <el-select
                  v-model="state.query.Currency"
                  placeholder="请选择销账币种"
                  style="width: 100%"
                  remote
                  :remote-method="getCurrentData"
                  :loading="state.currentLoading"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in state.current"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <span style="float: left"> {{ item.label }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="银行名称">
                <el-input
                  v-model="state.query.BankName"
                  size="small"
                  clearable
                  placeholder="请输入"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="银行账号">
                <el-input
                  v-model="state.query.BankAccount"
                  size="small"
                  clearable
                  placeholder="请输入"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="一般纳税人">
                <el-input
                  v-model="state.query.GeneralTaxpayer"
                  size="small"
                  clearable
                  placeholder="请输入"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="纳税人识别号">
                <el-input
                  v-model="state.query.TaxpayerNumber"
                  size="small"
                  clearable
                  placeholder="请输入"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="发票抬头">
                <el-input
                  v-model="state.query.InvoiceTitle"
                  size="small"
                  clearable
                  placeholder="请输入"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <div class="flex-container">
            <el-button
              type="primary"
              icon="search"
              @click="getList"
              size="small"
            >
              搜索
            </el-button>
            <el-button type="info" icon="refresh" @click="reset" size="small">
              重置
            </el-button>
          </div>
        </el-form>
      </div>
      <div style="margin-top: 8px">
        <div style="display: flex; margin-bottom: 8px">
          <div class="btn-box">
            <el-button
              type="primary"
              icon="DeleteFilled"
              @click="deleteStatement"
            >
              删除发票
            </el-button>
            <el-button type="primary" icon="EditPen" @click="editStatement">
              编辑发票
            </el-button>
            <el-button type="primary" @click="accountAduit(1)">
              确认
            </el-button>
            <el-button type="primary" @click="accountAduit(0)">
              取消
            </el-button>
            <el-button type="primary" icon="EditPen" @click="modifyMemo">
              设置发票号
            </el-button>
          </div>
          <div class="btn-right">
            <div v-if="state.curSumList.checkResult.length">
              <div class="tip"></div>
              <div class="label">
                {{ state.query.doctyp == 1 ? '应收' : '应付' }}已确认合计
              </div>
              <div
                class="label"
                v-for="(item, index) in state.curSumList.checkResult"
                :key="index"
              >
                {{ item.currency }}金额：{{
                  item.totalAmount ? item.totalAmount : 0
                }}
              </div>
            </div>
            <div v-if="state.curSumList.unCheckResult.length">
              <div class="tip"></div>
              <div class="label">
                {{ state.query.doctype == 1 ? '应收' : '应付' }}未确认合计
              </div>
              <div
                class="label"
                v-for="(item, index) in state.curSumList.unCheckResult"
                :key="index"
              >
                {{ item.currency }}金额：{{
                  item.totalAmount ? item.totalAmount : 0
                }}
              </div>
            </div>
          </div>
        </div>
        <AppPageTable
          stripe
          :data="state.tableData.data"
          @change="getList"
          :height="400"
          :option="state.tableData.option"
          v-loading="state.tableLoading"
          ref="tableRef"
          :singleHighLight="true"
          @cellClick="cellClick"
        >
          <el-table-column
            type="selection"
            width="40"
            align="center"
            fixed="left"
          />
          <el-table-column
            align="center"
            label="发票状态"
            showOverflowTooltip
            width="100"
          >
            <template #default="scope">
              {{ scope.row.docstatus == 1 ? '已确认' : '未确认' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="invoiceCode"
            align="center"
            label="发票号"
            showOverflowTooltip
          >
          </el-table-column>
          <el-table-column
            prop="doccode"
            align="center"
            label="开票单号"
            showOverflowTooltip
          >
            <template #default="scope">
              <div class="flex-center">
                <el-popover
                  placement="top"
                  :width="200"
                  trigger="hover"
                  :content="scope.row.doccode"
                >
                  <template #reference>
                    <div style="max-width: calc(100% - 35px)" class="ellipsis">
                      {{ scope.row.doccode }}
                    </div>
                  </template>
                </el-popover>
                <el-button
                  type="text"
                  style="padding: 2px"
                  @click="sigleDataDetails(scope.row)"
                >
                  明细
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="money"
            width="100"
            align="center"
            label="金额"
            showOverflowTooltip
          >
            <template #default="scope">
              {{ scope.row.money ? scope.row.money : 0 }}
            </template>
          </el-table-column>
          <el-table-column
            prop="invioceObjName"
            align="center"
            label="开票对象名称"
            showOverflowTooltip
          >
          </el-table-column>
          <el-table-column
            prop="invioceType"
            align="center"
            label="发票类型"
            showOverflowTooltip
          >
          </el-table-column>
          <el-table-column
            prop="invoiceTitle"
            align="center"
            label="发票抬头"
            showOverflowTooltip
          >
          </el-table-column>
          <el-table-column
            prop="invoiceDate"
            align="center"
            label="开票日期"
            showOverflowTooltip
          >
          </el-table-column>
          <el-table-column
            prop="bankName"
            label="银行名称"
            align="center"
            showOverflowTooltip
          >
          </el-table-column>
          <el-table-column
            prop="bankAccount"
            align="center"
            label="银行账号"
            showOverflowTooltip
          >
          </el-table-column>
          <el-table-column
            prop="generalTaxpayer"
            align="center"
            label="一般纳税人"
            showOverflowTooltip
          >
          </el-table-column>
          <el-table-column
            prop="currencyCode"
            align="center"
            label="币种"
            showOverflowTooltip
          >
          </el-table-column>
          <!-- <el-table-column
            prop="currencyName"
            align="center"
            label="币种名称"
            showOverflowTooltip
          >
          </el-table-column> -->
        </AppPageTable>

        <div
          :class="state.currentRow ? 'flex-between' : 'flex-end'"
          style="margin-top: 8px"
        >
          <div class="flex-start">
            <span
              v-if="state.currentRow"
              class="label"
              style="margin-right: 8px"
              >开票单号：{{ state.currentRow.doccode }}</span
            >
            <div v-if="state.curSumListSelected.length">
              <div class="tip"></div>
              <div class="label">汇总</div>
              <div
                class="label"
                v-for="(item, index) in state.curSumListSelected"
                :key="index"
              >
                {{ item.currency }}金额：{{ item.money ? item.money : 0 }}
              </div>
            </div>
          </div>
          <div class="btn-box" style="flex-grow: 0">
            <el-button
              type="primary"
              @click="addAccountFee"
              icon="Plus"
              :disabled="state.currentRow?.docstatus == 1"
            >
              添加明细
            </el-button>
            <el-button
              type="primary"
              icon="DeleteFilled"
              @click="deleteAccout"
              :disabled="state.currentRow?.docstatus == 1"
            >
              删除明细
            </el-button>
          </div>
        </div>

        <AppPageTable
          stripe
          :data="state.tableData.dataBottom"
          :height="300"
          :isPagination="true"
          :option="state.tableData.optionBottom"
          v-loading="state.tableData.optionBottom.loading"
          style="margin-top: 8px"
        >
          <el-table-column
            type="selection"
            width="40"
            align="center"
            fixed="left"
          />
          <el-table-column
            prop="doccode"
            width="200"
            align="center"
            label="业务编号"
            showOverflowTooltip
          >
          </el-table-column>
          <el-table-column
            prop="blNo"
            width="200"
            align="center"
            label="M提单号"
            showOverflowTooltip
          >
          </el-table-column>
          <el-table-column label="收付" align="center" showOverflowTooltip>
            <template #default="scope">
              {{ scope.row.isIncome == '0' ? '付' : '收' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="currency"
            align="center"
            label="币种"
            showOverflowTooltip
            width="100"
          >
          </el-table-column>
          <el-table-column
            prop="feeCode"
            align="center"
            label="费用代码"
            width="100"
            showOverflowTooltip
          >
          </el-table-column>
          <el-table-column
            prop="feeName"
            label="费用别名"
            align="center"
            width="200"
            showOverflowTooltip
          >
          </el-table-column>
          <el-table-column
            prop="price"
            label="单价"
            align="center"
            width="200"
            showOverflowTooltip
          >
          </el-table-column>
          <el-table-column
            label="数量"
            align="center"
            width="100"
            showOverflowTooltip
          >
            <template #default="scope">
              {{ scope.row.digit }}
            </template>
          </el-table-column>
          <el-table-column
            label="金额"
            align="center"
            width="100"
            showOverflowTooltip
          >
            <template #default="scope">
              {{ scope.row.totalmoney }}
            </template>
          </el-table-column>
          <el-table-column
            label="核销金额"
            align="center"
            width="100"
            showOverflowTooltip
          >
            <template #default="scope">
              {{ scope.row.verificationMoney }}
            </template>
          </el-table-column>
          <el-table-column
            label="结算对象名称"
            align="center"
            width="200"
            showOverflowTooltip
          >
            <template #default="scope">
              {{ scope.row.entFullname }}
            </template>
          </el-table-column>
          <el-table-column
            label="对账单号"
            align="center"
            width="200"
            showOverflowTooltip
          >
            <template #default="scope">
              {{ scope.row.balanceDoccode }}
            </template>
          </el-table-column>
        </AppPageTable>
      </div>
    </div>

    <InvoiceFeeFormModal
      ref="accountFormModalRef"
      @getList="getAddFee"
      :doctype="state.query.doctype"
    ></InvoiceFeeFormModal>

    <!-- 修改 -->
    <el-dialog
      v-model="state.show"
      :title="state.dailogTitle"
      width="520px"
      modal-class="modify-invoice-dailog"
      @close="invoiceClose"
    >
      <el-form label-suffix="：" label-width="80px" size="small">
        <el-form-item label="原发票号" v-if="state.originalInvoice">
          <el-input
            v-model="state.originalInvoice"
            placeholder="请输入"
            style="width: 100%"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="发票号">
          <el-input
            v-model="state.modfiyForm.invoiceCode"
            placeholder="请输入"
            style="width: 100%"
          ></el-input>
        </el-form-item>
        <el-form-item label="开票日期">
          <el-date-picker
            v-model="state.modfiyForm.invoice_date"
            type="date"
            size="small"
            style="width: 100%"
            format="YYYY-MM-DD"
            placeholder=" "
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="button-container">
          <el-button type="default" @click="state.show = false">取消</el-button>
          <el-button type="primary" @click="modifySubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- <InvoiceDialog
      ref="invoiceDialog"
      :hasAccount="true"
      @getList="getList"
    ></InvoiceDialog> -->
    <InvoiceDialogNew
      ref="invoiceDialog"
      :hasAccount="true"
      @getList="getList"
      :doctype="state.query.doctype"
    ></InvoiceDialogNew>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import AppPageTable, { useTableOption } from '@/components/AppPageTable2'
import request from '@/public/request'
import dayjs from 'dayjs'
import { MoreFilled } from '@element-plus/icons'
import { fileDownload } from '@/public/publicUtils'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import InvoiceFeeFormModal from './components/InvoiceFeeFormModal.vue'
import InvoiceDialog from './components/InvoiceDialog.vue'
import InvoiceDialogNew from './components/InvoiceDialogNew.vue'

const Route = useRoute()
const Router = useRouter()

const state = reactive({
  // 查询条件
  query: {
    Doccode: '', //开票单号
    InvoiceObjId: '', //开票对象ID
    InvoiceTypeId: '', //发票类型ID
    Currency: '', //币别
    BankName: '', //银行名称
    BankAccount: '', //银行账号
    GeneralTaxpayer: '', //一般纳税人
    TaxpayerNumber: '', //纳税人识别号
    doctype: 1, //1应收 0 应付
    InvoiceTitle: '' //发票抬头
  },
  // 原发票号
  originalInvoice: '',
  // 发票dailog标题
  dailogTitle: '登记发票号',
  // 主表选中的数据
  currentRow: '',
  //表格数据
  tableData: {
    data: [],
    option: useTableOption(),
    dataBottom: [],
    optionBottom: useTableOption()
  },
  tableLoading: false,
  // 展开
  hidden: false,
  // 结算对象的数据
  settlementList: [],
  settlementLoading: false,
  // 币种
  current: [],
  currentLoading: false,
  // 业务员
  salesman: [],
  salesmanLoading: false,
  // 发票类型
  InvoiceTypeList: [],
  // 核销状态
  WriteOffStatus: [
    {
      label: '全部',
      value: -2
    },
    {
      label: '未核销',
      value: 0
    },
    {
      label: '已核销',
      value: 1
    }
  ],
  // 审核状态
  aduitStatus: [
    {
      label: '全部',
      value: -2
    },
    {
      label: '未审核',
      value: 0
    },
    {
      label: '已审核',
      value: 1
    }
  ],
  //费用类型
  feenameList: [],
  feenameLoading: false,
  // 主表金额汇总
  curSumList: {
    checkResult: [],
    unCheckResult: []
  },
  // 币种数组
  curList: [],
  curSumListSelected: [],
  show: false,
  modfiyForm: {
    invoiceCode: '',
    invoiceIds: [],
    invoice_date: ''
  }
})

const tableRef = ref('')

const cellClick = () => {
  if (state.currentRow) {
    for (const iterator of state.tableData.data) {
      if (iterator.id == state.currentRow.id) {
        tableRef.value.$refs.tableRef.setCurrentRow(iterator)
      }
    }
  }
}

// 判断当前选择的数据是否可以删除
const judgeDeleteAble = (data) => {
  let canDelte = false
  for (const iterator of data) {
    if (iterator.docstatus == 1) {
      canDelte = true
      break
    }
  }
  return canDelte
}

// 新增费用明细成功
function getAddFee() {
  getList('bottom')
  getListBottom(state.currentRow)
}

// 获取币种类型
const getCurrentData = async (val) => {
  state.currentLoading = true
  let res = await request.get('/api/base/currency/dropdownlist', {
    keywords: val
  })
  state.current = res.map((item) => {
    return {
      label: item.currencyCode + '|' + item.currencyName,
      value: item.currencyCode
    }
  })
  state.currentLoading = false
}

// 查询条件整理
const queryCriteriaArrange = () => {
  let search = {
    PageIndex: state.tableData.option.page,
    PageSize: state.tableData.option.pageSize,
    ...JSON.parse(JSON.stringify(state.query))
  }
  let queryKeysList = Object.keys(state.query)
  for (const iterator of queryKeysList) {
    if (state.query[iterator] instanceof Array) {
      if (state.query[iterator].length === 0) {
        delete search[iterator]
      }
    } else {
      if (state.query[iterator] === -2) {
        search[iterator] = ''
      }
    }
  }
  return search
}

// 获取列表数据 typeDaptch:子表增删数据时操作
const getList = async (typeDaptch) => {
  let search = queryCriteriaArrange()
  state.tableLoading = true
  let res = await request.get('/api/invoice/QueryPageList', search)
  state.tableData.data = res.content.map((item) => {
    item.invoiceDate = item.invoiceDate.slice(0, item.invoiceDate.indexOf(' '))
    if (item.invoiceObj) {
      item.invioceObjName = item.invoiceObj?.entFullname
    } else {
      item.invioceObjName = ''
    }
    if (item.invoiceType) {
      item.invioceType = item.invoiceType?.invoicetypeName
    } else {
      item.invioceType = ''
    }
    return item
  })
  state.curSumList = res.totalMoney
  state.tableData.option.total = res.totalElements
  if (typeof typeDaptch != 'string') {
    state.currentRow = ''
    state.curSumListSelected = []
    state.tableData.dataBottom = []
    state.tableData.optionBottom.total = 0
  } else {
    for (const iterator of state.tableData.dataBottom) {
      if (iterator.id == state.currentRow.id) {
        tableRef.value.$refs.tableRef.setCurrentRow(iterator)
      }
    }
  }

  state.tableLoading = false
}

// 重置
const reset = () => {
  state.query = {
    Doccode: '', //开票单号
    InvoiceObjId: '', //开票对象ID
    InvoiceTypeId: '', //发票类型ID
    Currency: '', //币别
    BankName: '', //银行名称
    BankAccount: '', //银行账号
    GeneralTaxpayer: '', //一般纳税人
    TaxpayerNumber: '', //纳税人识别号
    doctype: 1,
    InvoiceTitle: '' //发票抬头
  }
  getList()
}

// 删除明细
const deleteAccout = () => {
  if (state.tableData.optionBottom.selected.length == 0) {
    ElMessage.warning('请至少选择一条数据！')
    return
  }
  let ids = []
  for (const iterator of state.tableData.optionBottom.selected) {
    ids.push(iterator.id)
  }

  ElMessageBox.confirm('确定删除该费用', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let res = await request.post(`/api/invoice/removeInvoiceFee`, {
        idArray: ids
      })
      if (res.status) {
        getList('bottom')
        getListBottom(state.currentRow)
        ElMessage.success('删除成功')
      } else {
        ElMessage.warning(res.message)
      }
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}

const invoiceDialog = ref()

// 删除开票
const deleteStatement = async () => {
  if (state.tableData.option.selected.length == 0) {
    ElMessage.warning('请至少选择一条数据！')
    return
  }
  if (judgeDeleteAble(state.tableData.option.selected)) {
    ElMessage.warning('当前选中的发票数据已确认')
    return
  }
  let ids = []
  for (const iterator of state.tableData.option.selected) {
    ids.push(iterator.id)
  }
  ElMessageBox.confirm('确定删除该发票吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let res = await request.post(`/api/invoice/delete`, {
        idArray: ids
      })
      if (res.status) {
        getList()
        state.tableData.dataBottom = []
        ElMessage.success('成功')
      } else {
        ElMessage.warning(res.message)
      }
    })
    .catch(() => {
      // ElMessage.info('取消操作')
    })
}
// 编辑开票
const editStatement = () => {
  if (judgeDeleteAble(state.tableData.option.selected)) {
    ElMessage.warning('当前选中的发票数据已确认')
    return
  }
  if (state.tableData.option.selected.length != 1) {
    ElMessage.warning('请选择一条数据！')
    return
  }

  invoiceDialog.value.openDialog(state.tableData.option.selected[0])
}

const accountStatementRef = ref()

// 对账单确认和取消
async function accountAduit(val) {
  let selectedList = state.tableData.option.selected
  if (selectedList.length < 1) {
    ElMessage.warning('请至少选择一条发票')
    return
  }
  //需要确认的数据
  let hasInvoiceNumber = false
  for (const item of selectedList) {
    if (!item.invoiceCode && val == 1) {
      hasInvoiceNumber = true
      break
    }
  }
  if (hasInvoiceNumber) {
    ElMessage.warning('选中的数据中存在没有发票号的数据')
    return
  }
  let falg = false
  let ids = []
  for (const iterator of selectedList) {
    ids.push(iterator.id)
    if (
      (val == 1 && iterator.docstatus == 1) ||
      (val == 0 && iterator.docstatus == 0)
    ) {
      falg = true
    }
  }
  if (falg) {
    if (val == 1) {
      ElMessage.warning('选中的数据中存在已确认的数据')
      return
    }
    if (val == 0) {
      ElMessage.warning('选中的数据中存在未确认的数据')
      return
    }
  }
  let res = await request.post(`/api/invoice/checkInvoiceStatus`, {
    ids: ids,
    checkStatus: val
  })
  if (res.status) {
    getList()
    state.tableData.dataBottom = []
    ElMessage.success('成功')
  } else {
    ElMessage.warning(res.message)
  }
}

// 底部表格数据
const getListBottom = async (row) => {
  if (!row) {
    return
  }
  let ids = []
  ids.push(row.id)
  let res = await request.post('/api/invoice/GetFeeListByInvoiceIds', {
    idArray: ids
  })
  state.tableData.optionBottom.loading = true
  state.tableData.dataBottom = res
  computeCurencySum(res, 'top')
  state.tableData.optionBottom.loading = false
}

const accountFormModalRef = ref()

// 添加费用
const addAccountFee = async () => {
  if (!state.currentRow) {
    ElMessage.warning('请先选择一条发票！')
    return
  }
  accountFormModalRef.value.open(state.currentRow)
}

// 头部表格单选框变动
const sigleDataDetails = (row) => {
  state.currentRow = row
  tableRef.value.$refs.tableRef.setCurrentRow(row)
  getListBottom(row)
}

// 计算当前选中的币种合计
const computeCurencySum = (select, tableType) => {
  state.curSumListSelected = []
  let curList = []
  select.forEach((item) => {
    let totalMoney = item.totalmoney
      ? item.totalmoney * (item.isIncome == state.query.doctype ? 1 : -1)
      : 0
    if (item.currency) {
      if (curList.indexOf(item.currency) == -1) {
        curList.push(item.currency)
        let curObj = {
          currency: item.currency,
          money: totalMoney
        }

        state.curSumListSelected.push(curObj)
      } else {
        let sumList = []
        sumList = state.curSumListSelected
        for (const iterator of sumList) {
          if (iterator.currency === item.currency) {
            iterator.money += totalMoney
          }
        }
      }
    }
  })
}

// 获取结算对象的数据
const getBusDetail = async (val) => {
  state.settlementLoading = true
  let res = await request.get('/api/buenterprise/dropdownlist', {
    KeyWords: val
  })
  res.forEach((item) => {
    item.label = item.entCode
    item.value = item.id
  })
  state.settlementList = res
  state.settlementLoading = false
}

// 获取业务员
const getSalesman = async (val) => {
  this.salesmanLoading = true
  let res = await request.get('/api/user/userList', {
    keyword: val
  })
  res.forEach((item) => {
    item.label = item.nickName
    item.value = item.id
  })
  state.salesman = res
  state.salesmanLoading = false
}

// 获取费用类型
const getFeeType = async (val) => {
  state.feenameLoading = true
  let res = await request.get('/api/base/feetype/query', {
    KeyWords: val
  })
  res.content.forEach((item) => {
    item.label = item.feeName
    item.value = item.feeName
  })
  state.feenameList = res.content
  state.feenameLoading = false
}

// 获取发票类型
const getInvoiceList = async () => {
  let res = await request.get('/api/base/invoice/queryList')
  res.forEach((item) => {
    item.value = item.id
    item.label = item.invoicetypeName
  })
  state.InvoiceTypeList = res
}

// 修改发票号
const modifyMemo = () => {
  if (state.tableData.option.selected.length < 1) {
    ElMessage.warning('请至少选择一条发票！')
    return
  }
  if (judgeDeleteAble(state.tableData.option.selected)) {
    ElMessage.warning('当前选中的发票数据已确认')
    return
  }
  state.modfiyForm = {
    invoiceIds: [],
    invoiceCode: '',
    invoice_date: ''
  }
  // 是否选择的数据是否已有发票号
  let hasInvoice = false
  for (const iterator of state.tableData.option.selected) {
    state.modfiyForm.invoiceIds.push(iterator.id)
    if (iterator.invoiceCode) {
      hasInvoice = true
    }
  }
  if (hasInvoice && state.tableData.option.selected.length != 1) {
    ElMessage.warning(
      '选择的发票中存在已有发票号的数据,且修改发票号只能选择一条发票'
    )
    return
  }
  state.dailogTitle = '登记发票号'
  if (hasInvoice && state.tableData.option.selected.length == 1) {
    state.originalInvoice = state.tableData.option.selected[0].invoiceCode
    state.dailogTitle = '修改发票号'
  }
  state.show = true
}

const modifySubmit = async () => {
  if (!state.modfiyForm.invoiceCode || !state.modfiyForm.invoice_date) {
    ElMessage.warning('请填写发票号和开票日期')
    return
  }
  let res = await request.post(
    '/api/invoice/RegisterInvoiceNumber',
    state.modfiyForm
  )
  if (res.status) {
    getList()
    ElMessage.success('成功')
    state.show = false
  } else {
    ElMessage.warning(res.message)
  }
}
const invoiceClose = () => {
  state.modfiyForm = {
    invoiceIds: [],
    invoiceCode: '',
    invoice_date: ''
  }
  state.originalInvoice = ''
}

onMounted(() => {
  getCurrentData()
  getInvoiceList()
  getList()
})
</script>

<style lang="scss" scoped>
@import '@/styles/financial.scss';
.form-container {
  border: 1px solid #e8e8e8;
  padding: 6px 6px 6px 8px;
  background-color: #ffffff;

  :deep(.el-form-item--small .el-form-item__label) {
    font-size: 12px;
    color: rgba(0, 0, 0, 0.85);
  }

  :deep(.el-input--suffix .el-input__inner) {
    padding-right: 4px;
  }

  :deep(.el-form--inline .el-form-item) {
    display: flex;
    margin-right: 0;
  }

  :deep(.el-form-item--small.el-form-item) {
    margin-bottom: 8px;
  }
}

.btn-box {
  flex-shrink: 0;
}

.btn-right {
  display: flex;
  flex: 1 1 0%;
}

.tip {
  display: inline-block;
  background: #2867c9;
  width: 4px;
  height: 20px;
  vertical-align: middle;
  margin-left: 8px;
}

.label {
  margin: 0 8px;
  display: inline-block;
  font-size: 14px;
  font-weight: 600;
}

.flex-container {
  display: flex;
}

.doccode-text {
  color: rgb(24, 144, 255);
  cursor: pointer;
}

.button-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>

<style lang="scss">
// .accountsReconciled-dailog {
//     .el-dialog__header {
//         border-bottom: 1px solid #e8e8e8;
//     }

//     .el-dialog__footer {
//         border-top: 1px solid #e8e8e8;
//     }
// }
</style>
